﻿using NPinyin;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp.WxAppJson;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wq.Extensions.Common;
using Wq.Extensions.Repository;
using Wq.ManagerService;
using Wq.ManagerService.Entities;
using Wq.ManagerService.Models;
using Wq.ManagerService.Models.Region;
using Wq.MeetingService;
using Wq.MeetingService.Models;
using Wq.Model;

namespace Wq.Application
{
    /// <summary>
    /// 已开通城市
    /// </summary>
    public class OpenCityApplication : BaseApplication
    {
        private readonly OpenCityService service;
        private readonly BusinessCircleService businessCircleService;
        private readonly VenueService venueService;
        private readonly RedisBaseRepository redisRepository;
        private readonly RegionService regionService;
        private readonly LogService logService;
        public OpenCityApplication(OpenCityService service, 
            VenueService venueService,
            RegionService regionService,
            RedisBaseRepository redisRepository,
            BusinessCircleService businessCircleService,
            LogService logService)
        {
            this.service = service;
            this.venueService = venueService;
            this.regionService = regionService;
            this.redisRepository = redisRepository;
            this.businessCircleService = businessCircleService;
            this.logService = logService;   
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="info"></param>
        public void Create(OpenCityInfo info)
        {
            var region = regionService.GetById(info.RegionId);
            info.FirstLetter = Pinyin.GetPinyin(region.Name).Substring(0, 1);
            service.Create(info);

            string msg = $"添加城市【{region.Name}】";
            logService.Create(LogModule.OpenCity, msg);
            redisRepository.Remove(SysCacheKey.OpenCityList);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="info"></param>
        public void Save(OpenCityInfo info)
        {
            var old = service.Details(info.RegionId);
            var oldRegion = regionService.GetById(old.RegionId);
            var region = regionService.GetById(info.RegionId);
            info.FirstLetter = Pinyin.GetPinyin(region.Name).Substring(0, 1);
            service.Save(info);
            redisRepository.Remove(SysCacheKey.OpenCity(info.RegionId));
            redisRepository.Remove(SysCacheKey.OpenCityList);

            string msg = $"修改城市【{oldRegion.Name}】";
            if (oldRegion.Name != region.Name)
                msg += $" 名称由【{oldRegion.Name}】变为【{region.Name}】";
            logService.Create(LogModule.OpenCity, msg);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="regionId"></param>
        public void Delete(int regionId)
        {
           var model = service.Details(regionId);
           var businessIds = model.Business.Select(p => p.Id).ToList();
            if(venueService.Count(p => businessIds.Contains(p.BusinessId)) > 0)
                throw new MyException("该城市下存在场馆，不能删除");
            service.Delete(regionId);
            redisRepository.Remove(SysCacheKey.OpenCity(regionId));
            redisRepository.Remove(SysCacheKey.OpenCityList);

            var region = regionService.GetById(regionId);
            string msg = $"删除城市【{region.Name}】";
            logService.Create(LogModule.OpenCity, msg);

        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="regionId"></param>
        /// <returns></returns>
        public OpenCityInfo Details(int regionId) =>  
            redisRepository.Get(SysCacheKey.OpenCity(regionId), () =>
            {
               return service.Details(regionId);
            }).Result;
          
        /// <summary>
        /// 修改排序
        /// </summary>
        /// <param name="regionId"></param>
        /// <param name="sequence"></param>
        public void UpdateGuestSequence(int regionId, long sequence)
        {
            service.UpdateSequence(regionId, sequence);
            var model = service.Details(regionId);
            redisRepository.Remove(SysCacheKey.OpenCity(regionId));
            redisRepository.Remove(SysCacheKey.OpenCityList);

        }

        /// <summary>
        /// 删除商圈
        /// </summary>
        /// <param name="id"></param>
        public  void Deletebusiness(long id)
        {
            var business = businessCircleService.GetById(id);
            businessCircleService.DeleteById(id);
            var city = service.Details(business.CityRegionId);
            var region = regionService.GetById(city.RegionId);
            string msg = $"删除城市【{region.Name}】，商业圈【{business.Name}】";
            logService.Create(LogModule.OpenCity, msg);
            redisRepository.Remove(SysCacheKey.OpenCity(business.CityRegionId));
            redisRepository.Remove(SysCacheKey.OpenCityList);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="pageModel"></param>
        /// <returns></returns>
        public MessageModel List(PageModel<OpenCityQuery> pageModel) => new MessageModel { Data = service.List(pageModel), Count = pageModel.Page.Num };

        /// <summary>
        /// 全部城市
        /// </summary>
        /// <returns></returns>
        public List<OpenCityView> List() =>
               redisRepository.Get(SysCacheKey.OpenCityList, () => {
                  return service.List();
            }).Result;

        /// <summary>
        /// 修改是否热门
        /// </summary>
        /// <param name="regionId"></param>
        /// <param name="hot"></param>
        public void UpdateHot(int regionId, bool hot)
        {
            service.UpdateHot(regionId, hot);
            redisRepository.Remove(SysCacheKey.OpenCity(regionId));
        }

        /// <summary>
        /// 城市商业圈
        /// </summary>
        /// <param name="regionId"></param>
        /// <returns></returns>
        public List<BusinessCircleInfo> GetListByRegionId(int regionId) => businessCircleService.GetList(p => p.CityRegionId == regionId);

        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, Dictionary<int, string>> GruopCity()
        {

            var list = List();
            var result = new Dictionary<string, Dictionary<int, string>>();
            result.Add("热门", list.Where(p => p.Hot).ToList().ToDictionary(p => p.RegionId, p => p.Name));
            foreach (var item in list.OrderBy(p => p.FirstLetter).GroupBy(p => p.FirstLetter))
                result.Add(item.Key.ToUpper(), item.ToDictionary(p => p.RegionId, p => p.Name));
            return result;
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="regionId"></param>
        /// <returns></returns>
        public OpenCityView Details(string name) => service.Details(name);
    }
}
